
import 'package:get/get.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import '../../../config/app_constants.dart';
import '../../../data/services/remote_config_service.dart';
import '../../../data/models/wiki_config.dart';
import '../../main_screen/controllers/main_screen_controller.dart';

class HomeController extends GetxController {
  // WebView控制器
  InAppWebViewController? webViewController;
  
  // 加载状态
  final RxBool isLoading = true.obs;
  
  // 加载进度
  final RxDouble loadingProgress = 0.0.obs;
  
  // 页面标题
  final RxString pageTitle = ''.obs;
  
  // 错误状态
  final RxBool hasError = false.obs;
  final RxString errorMessage = ''.obs;
  
  // 是否可以后退
  final RxBool canGoBack = false.obs;
  
  // 是否可以前进
  final RxBool canGoForward = false.obs;

  // 远程配置服务
  final RemoteConfigService _remoteConfigService = Get.find<RemoteConfigService>();
  
  // Wiki配置
  final Rx<WikiConfig?> wikiConfig = Rx<WikiConfig?>(null);
  
  // 搜索结果
  final RxList<WikiSearchResult> searchResults = <WikiSearchResult>[].obs;
  
  // 搜索状态
  final RxBool isSearching = false.obs;
  final RxString searchQuery = ''.obs;

  // 获取主屏幕控制器
  MainScreenController get mainController => Get.find<MainScreenController>();

  @override
  void onInit() {
    super.onInit();
    // 监听主控制器的Wiki URL变化
    ever(mainController.currentWikiUrl, (String url) {
      loadUrl(url);
    });
    
    // 加载Wiki配置
    _loadWikiConfig();
  }
  
  // 加载Wiki配置
  Future<void> _loadWikiConfig() async {
    try {
      final config = await _remoteConfigService.getWikiConfig();
      wikiConfig.value = config;
    } catch (e) {
      print('Error loading wiki config: $e');
    }
  }

  // WebView初始化完成
  void onWebViewCreated(InAppWebViewController controller) {
    webViewController = controller;
  }

  // 页面开始加载
  void onLoadStart(InAppWebViewController controller, WebUri? url) {
    isLoading.value = true;
    hasError.value = false;
    errorMessage.value = '';
    loadingProgress.value = 0.0;
  }

  // 页面加载完成
  void onLoadStop(InAppWebViewController controller, WebUri? url) {
    isLoading.value = false;
    loadingProgress.value = 1.0;
    _updateNavigationState();
  }

  // 加载进度更新
  void onProgressChanged(InAppWebViewController controller, int progress) {
    loadingProgress.value = progress / 100.0;
  }

  // 页面标题更新
  void onTitleChanged(InAppWebViewController controller, String? title) {
    if (title != null && title.isNotEmpty) {
      pageTitle.value = title;
    }
  }

  // 页面加载错误
  void onLoadError(InAppWebViewController controller, WebUri? url, int code, String message) {
    isLoading.value = false;
    hasError.value = true;
    errorMessage.value = message.isNotEmpty ? message : AppConstants.errorLoadingWiki;
    
    Get.snackbar(
      '加载失败',
      errorMessage.value,
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 3),
    );
  }

  // 加载指定URL
  Future<void> loadUrl(String url) async {
    if (webViewController != null && url.isNotEmpty) {
      try {
        await webViewController!.loadUrl(
          urlRequest: URLRequest(url: WebUri(url)),
        );
      } catch (e) {
        print('Error loading URL: $e');
        hasError.value = true;
        errorMessage.value = '无法加载页面: $e';
      }
    }
  }

  // 刷新页面
  Future<void> refresh() async {
    if (webViewController != null) {
      try {
        await webViewController!.reload();
      } catch (e) {
        print('Error refreshing page: $e');
      }
    }
  }

  // 后退
  Future<void> goBack() async {
    if (webViewController != null && canGoBack.value) {
      try {
        await webViewController!.goBack();
        _updateNavigationState();
      } catch (e) {
        print('Error going back: $e');
      }
    }
  }

  // 前进
  Future<void> goForward() async {
    if (webViewController != null && canGoForward.value) {
      try {
        await webViewController!.goForward();
        _updateNavigationState();
      } catch (e) {
        print('Error going forward: $e');
      }
    }
  }

  // 更新导航状态
  Future<void> _updateNavigationState() async {
    if (webViewController != null) {
      try {
        canGoBack.value = await webViewController!.canGoBack();
        canGoForward.value = await webViewController!.canGoForward();
      } catch (e) {
        print('Error updating navigation state: $e');
      }
    }
  }

  // 搜索
  Future<void> search(String query) async {
    if (query.trim().isEmpty) {
      searchResults.clear();
      return;
    }
    
    searchQuery.value = query;
    isSearching.value = true;
    
    try {
      // 执行双语搜索
      final results = await _performBilingualSearch(query);
      searchResults.assignAll(results);
      
      // 如果有搜索结果，加载第一个结果
      if (results.isNotEmpty) {
        final firstResult = results.first;
        await loadUrl(firstResult.wiki.url);
        
        // 添加到历史记录
        _addToHistory(firstResult);
      } else {
        // 使用传统搜索方式
        final searchUrl = mainController.getSearchUrl(query);
        await loadUrl(searchUrl);
      }
    } catch (e) {
      print('Error searching: $e');
      // 回退到传统搜索
      final searchUrl = mainController.getSearchUrl(query);
      await loadUrl(searchUrl);
    } finally {
      isSearching.value = false;
    }
  }
  
  // 执行双语搜索
  Future<List<WikiSearchResult>> _performBilingualSearch(String query) async {
    final config = wikiConfig.value;
    if (config == null) return [];
    
    final results = <WikiSearchResult>[];
    
    // 搜索所有Wiki项目
    for (final item in config.wikis) {
      if (item.matchesSearch(query, 'zh')) {
        final searchResult = WikiSearchResult(
          wiki: item,
          relevance: _calculateRelevance(item, query),
          matchedFields: _getMatchedFields(item, query),
        );
        results.add(searchResult);
      }
    }
    
    // 按相关性排序
    results.sort((a, b) => b.relevance.compareTo(a.relevance));
    
    return results;
  }
  
  // 添加到历史记录
  void _addToHistory(WikiSearchResult result) {
    // TODO: 实现历史记录功能
    print('Adding to history: ${result.wiki.name}');
  }
  
  // 计算相关性分数
  double _calculateRelevance(WikiItem item, String query) {
    final lowerQuery = query.toLowerCase();
    double score = 0.0;
    
    if (item.name.toLowerCase().contains(lowerQuery)) score += 1.0;
    if (item.nameCn.toLowerCase().contains(lowerQuery)) score += 1.0;
    if (item.nameEn.toLowerCase().contains(lowerQuery)) score += 1.0;
    if (item.description.toLowerCase().contains(lowerQuery)) score += 0.5;
    if (item.tags.any((tag) => tag.toLowerCase().contains(lowerQuery))) score += 0.3;
    
    return score;
  }
  
  // 获取匹配的字段
  List<String> _getMatchedFields(WikiItem item, String query) {
    final lowerQuery = query.toLowerCase();
    final matchedFields = <String>[];
    
    if (item.name.toLowerCase().contains(lowerQuery)) matchedFields.add('name');
    if (item.nameCn.toLowerCase().contains(lowerQuery)) matchedFields.add('nameCn');
    if (item.nameEn.toLowerCase().contains(lowerQuery)) matchedFields.add('nameEn');
    if (item.description.toLowerCase().contains(lowerQuery)) matchedFields.add('description');
    
    return matchedFields;
  }
  
  // 清除搜索结果
  void clearSearchResults() {
    searchResults.clear();
    searchQuery.value = '';
  }

  // 获取当前URL
  Future<String?> getCurrentUrl() async {
    if (webViewController != null) {
      try {
        final url = await webViewController!.getUrl();
        return url?.toString();
      } catch (e) {
        print('Error getting current URL: $e');
      }
    }
    return null;
  }

  // 执行JavaScript
  Future<dynamic> evaluateJavascript(String source) async {
    if (webViewController != null) {
      try {
        return await webViewController!.evaluateJavascript(source: source);
      } catch (e) {
        print('Error evaluating JavaScript: $e');
      }
    }
    return null;
  }

  // 清理资源
  @override
  void onClose() {
    webViewController = null;
    super.onClose();
  }
}

